<?php

namespace iBrand\Shop\Server\Http\Controllers;

use iBrand\Component\Product\Models\Goods;
use iBrand\Component\Product\Models\Product;
use iBrand\Server\Http\Controllers\Controller;
use iBrand\Shop\Core\Models\Clerk;
use iBrand\Shop\Core\Models\Shop;
use iBrand\Shop\Core\Repositories\BarCodeRepository;
use iBrand\Component\Product\Repositories\ProductRepository;
use iBrand\Component\Product\Repositories\GoodsRepository;
use iBrand\Server\Exception\UserExistsException;
use iBrand\Shop\Core\Service\WeProgramService;
use Illuminate\Auth\Events\Login;
use iBrand\Component\Product\Models\Specification;
use Illuminate\Http\Request;
use League\OAuth2\Server\Exception\OAuthServerException;
use RuntimeException;
use Validator;
use Hash;

class BarCodeController extends Controller
{
    private $barCodeRepository;
    private $productRepository;
    private $goodsRepository;
    private $weProgramService;

    public function __construct(
        BarCodeRepository $barCodeRepository,
        ProductRepository $productRepository,
        GoodsRepository $goodsRepository,
        WeProgramService $weProgramService
    )
    {
        $this->barCodeRepository = $barCodeRepository;
        $this->productRepository = $productRepository;
        $this->goodsRepository = $goodsRepository;
        $this->weProgramService = $weProgramService;
    }

    /**
     * 导购扫条形码方法
     * @param $code
     * @return \Dingo\Api\Http\Response
     */
    public function index($code)
    {
        $data = [];
        if ($code = $this->barCodeRepository->findWhere(['bar_code' => $code])->last()) {
            if (!empty($code->sku)) {
                $res = $this->productRepository->findOneBySku($code->sku);
                if ($res) {
                    $data['name'] = $res->name;
                    $data['goods_id'] = $res->goods_id;
                    $data['sku_id'] = $res->id;
                    $data['sku'] = $res->sku;
                    $data['sell_price'] = $res->sell_price;
                    $data['img'] = $this->getImageCdnUrl($res->goods->img);
                    $data['specsText'] = $res->SpecsText;
                }
            }
        }

        return $this->api($data, true, 200, '');
    }

    private function getImageCdnUrl($value)
    {
        $replace_url = settings('store_img_replace_url') ? settings('store_img_replace_url') : url('/');
        if (settings('store_img_cdn_status') AND $url = settings('store_img_cdn_url')) {
            $value = str_replace('http://' . $replace_url, $url, $value);
            /* return preg_replace_callback('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i', function ($r) use ($url) {
                 return (preg_replace("/(http:\/\/|https:\/\/)([^\/]+)/i", $url, $r[0]));
             }, $value);*/
        }

        return $value;
    }


    /**
     * 生成门店商品小程序二维码
     * @return \Dingo\Api\Http\Response
     */
    public function getMiniQrCode()
    {
        $result = $this->weProgramService->getWxaCodeUrl(request('path'), request('shop_id'), request('goods_id'));
        if ($result) {
            return $this->api(['url' => env('APP_URL') . $result[1]]);
        }
        return $this->api([], false, 400, '生成失败，请稍后重试');
    }

    public function getScanData()
    {
        $code = request('code');
        $product = Product::where('sku', $code)->orWhere('bar_code', $code)->first();
        if (!$product) {
            $goods = Goods::where('goods_no', $code)->first(); //这里goods_no字段为临时，后续需要增加新的字段
            if (!$goods) {
                return $this->api([], false, 400, '商品不存在');
            }
            $data = [
                'goods_id' => $goods->id,
                'is_sku' => false,   //是否为SKU
                'sku_id' => '',
                'no_sku' => $goods->products->count() > 0 ? false : true  //是否为无规格商品
            ];
            return $this->api($data);
        }
        $data = [
            'goods_id' => $product->goods_id,
            'is_sku' => true,
            'sku_id' => $product->id,
            'no_sku' => false
        ];

        return $this->api($data);

    }

}
